package org.association.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import org.association.dao.NormalProposalDao;
import org.association.dao.OrganizationDao;
import org.association.dao.VoteRecordDao;
import org.association.dto.NormalProposalDTO;
import org.association.entity.NormalProposal;
import org.association.entity.OrganizationEntity;
import org.association.entity.UserEntity;
import org.association.entity.VoteRecord;
import org.association.link.LinkUtil;
import org.association.service.NormalProposalService;
import org.association.service.TradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;

@Service
public class NormalProposalServiceImpl extends ServiceImpl<NormalProposalDao, NormalProposal> implements NormalProposalService {
    @Autowired
    NormalProposalDao normalProposalMapper;

    @Autowired
    OrganizationDao organizationDao;

    @Autowired
    VoteRecordDao voteRecordDao;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TradeService tradeService;

    @Override
    public ArrayList<NormalProposal> getAllProposals(String orgID) {
//        ArrayList<NormalProposal> results = new ArrayList<>();
//        for (int i = 1; i <= 6; i++) {
//            NormalProposal np = new NormalProposal();
//            np.setProposalName("测试用例：" + Integer.toString(i));
//            np.setPublishTime(new Date());
//            np.setActivityPlace("地点-深圳");
//            np.setActivityContent("活动内容" + Integer.toString(i));
//            np.setActivityBudgetList("预算清单" + Integer.toString(i));
//            np.setActivityBudgetSum(new BigDecimal(100.0));
//            np.setPublishUserId("001");
//            np.setOrganizationId("001");
//            np.setProposalId(UUID.randomUUID().toString());
//            results.add(np);
//        }
//        this.saveBatch(results);
        QueryWrapper<NormalProposal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organization_id", orgID); // 表示 where age > 20
        ArrayList<NormalProposal> results = (ArrayList<NormalProposal>) normalProposalMapper.selectList(queryWrapper);
        Collections.reverse(results);
        return results;
    }

    @Override
    public NormalProposal addNormalProposalDTO(NormalProposalDTO normalProposalDTO) {
        NormalProposal np = new NormalProposal(normalProposalDTO);
        List<String> users = organizationDao.getUsersByOrganizationID(np.getOrganizationId());
        int targetSum = (int) (users.size() * 0.5);
        if (targetSum == 0){
            targetSum = 1;
        }
        /**
         * 对接区块链接口
         */
        Integer proposalId = LinkUtil.addProposal(restTemplate, targetSum);
        np.setProposalId(Integer.toString(proposalId));
        np.setTargetPeopleSum(Long.valueOf(targetSum));
        normalProposalMapper.insert(np);
        return np;
    }

    @Override
    public Integer voteOneProposal(String proposalID, String userID, Integer isSuppor) {
        Integer stat = 0;
        if (isSuppor == 1){
            Integer result = LinkUtil.vote(restTemplate, userID, Integer.valueOf(proposalID), isSuppor);
            System.out.println(result);
            //投票操作成功
            if (result == 0 || result == 1){
                normalProposalMapper.voteProposalAgreeUpdate(proposalID);
                stat = 1;
                VoteRecord voteRecord = new VoteRecord();
                voteRecord.setUserId(userID);
                voteRecord.setStatu(1);
                voteRecord.setProposalId(proposalID);
                voteRecordDao.insert(voteRecord);
                if (result == 1){
                    // 在数据库更新 proposal 状态
                    normalProposalMapper.setProposalSucceed(proposalID);
                    System.out.println(proposalID);
                    doVoteSucceed(proposalID);
                }
            }else{
                //投票发生错误
                stat = -1;
            }
        }else{
            VoteRecord voteRecord = new VoteRecord();
            voteRecord.setUserId(userID);
            voteRecord.setStatu(0);
            voteRecord.setProposalId(proposalID);
            voteRecordDao.insert(voteRecord);
            normalProposalMapper.voteProposalDisagreeUpdate(proposalID);
        }
        return stat;
    }

    public boolean doVoteSucceed(String proposalID){
        ArrayList<String> users = getAllAgreePeople(proposalID);
        for(int i = 0; i < users.size(); i++){
            System.out.println(users.get(i));
        }
        NormalProposal  normalProposal = getOneProposalByID(proposalID);
        System.out.println(normalProposal);
        String orgAddress = organizationDao.getAddressFromOrgId(normalProposal.getOrganizationId());
        System.out.println(orgAddress);
        int sum = (int)Math.ceil(normalProposal.getActivityBudgetSum().floatValue() / normalProposal.getTargetPeopleSum());
        tradeService.batchTransferWBA(users, orgAddress, sum);
        return true;
    }

    public NormalProposal getOneProposalByID(String proposalID) {
//        NormalProposal np = new NormalProposal();
//        int i = new Random().nextInt();
//        np.setProposalName("测试用例：" + Integer.toString(i));
//        np.setPublishTime(new Date());
//        np.setActivityPlace("地点-深圳");
//        np.setActivityContent("活动内容" + Integer.toString(i));
//        np.setActivityBudgetList("预算清单" + Integer.toString(i));
//        np.setActivityBudgetSum(new BigDecimal(100.0));
//        np.setPublishUserId("001");
//        np.setOrganizationId("001");
//        np.setProposalId(proposalID);
        QueryWrapper<NormalProposal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("proposal_id", proposalID);
        return normalProposalMapper.selectOne(queryWrapper);
    }

    @Override
    public VoteRecord getVoteRecordById(String proposalID, String userID) {
        VoteRecord voteRecord = voteRecordDao.getVoteRecordById(proposalID, userID);
        if(voteRecord == null){
            voteRecord = new VoteRecord();
            voteRecord.setProposalId(proposalID);
            voteRecord.setUserId(userID);
            voteRecord.setStatu(-1);
        }
        return voteRecord;
    }

    @Override
    public ArrayList<String> getAllAgreePeople(String proposalID) {
        return  voteRecordDao.getAgreePeopleByProposalId(proposalID, 1);
    }


}
